package com.suse.service.admin.edu.listener.excel;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.suse.common.config.response.ApiException;
import com.suse.common.util.core.StringUtil;
import com.suse.service.admin.edu.model.entity.Subject;
import com.suse.service.admin.edu.model.excel.SubjectExcel;
import com.suse.service.admin.edu.service.SubjectService;

public class SubjectExcelAnalysisEventListener extends AnalysisEventListener<SubjectExcel> {

    private final SubjectService subjectService = SpringUtil.getBean(SubjectService.class);

    // 遇到大文件容易 OOM
    // private final List<Subject> firstSubjectList = new ArrayList<>();
    // private final List<Subject> secendSubjectList = new ArrayList<>();

    @Override
    public void invoke(SubjectExcel subjectExcel, AnalysisContext analysisContext) {
        // 判断导入数据格式是否正确
        if (ObjectUtil.isNull(subjectExcel)) {
            throw new ApiException("导入失败，文件数据不能为为空！");
        }
        String firstSubjectName = subjectExcel.getFirstSubjectName();
        String secondSubjectName = subjectExcel.getSecondSubjectName();
        if (StringUtil.isEmpty(firstSubjectName)) {
            throw new ApiException("导入失败，一级分类不能为空！");
        }
        // 添加一级分类
        Subject firstSubject = getFirstSubjectByName(firstSubjectName);
        if (ObjectUtil.isNull(firstSubject)) {
            firstSubject = new Subject();
            firstSubject.setParentId("0");
            firstSubject.setTitle(subjectExcel.getFirstSubjectName());
            subjectService.save(firstSubject);
        }
        if (StringUtil.isEmpty(secondSubjectName)) {
            return;
        }
        // 获取一级分类 ID
        String parentId = firstSubject.getId();
        // 添加二级分类
        Subject secondSubject = getSecondSubjectByName(secondSubjectName);
        if (ObjectUtil.isNull(secondSubject)) {
            secondSubject = new Subject();
            secondSubject.setParentId(parentId);
            secondSubject.setTitle(subjectExcel.getSecondSubjectName());
            subjectService.save(secondSubject);
        }
    }

    // 通过名称获取一级分类
    private Subject getFirstSubjectByName(String name) {
        return subjectService.lambdaQuery()
                .eq(Subject::getTitle, name)
                .eq(Subject::getParentId,"0")
                .one();
    }

    // 通过名称获取二级分类
    private Subject getSecondSubjectByName(String name) {
        return subjectService.lambdaQuery()
                .eq(Subject::getTitle, name)
                .ne(Subject::getParentId,"0")
                .one();
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

}
